package com.mnb.beidou.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * MQTT连接监听器
 * 监控MQTT连接状态并处理重连
 */
@Component
public class MqttConnectionListener {
    
    private static final Logger logger = LoggerFactory.getLogger(MqttConnectionListener.class);
    
    @Autowired(required = false)
    private MqttPahoMessageDrivenChannelAdapter mqttAdapter;
    
    private final AtomicBoolean isConnecting = new AtomicBoolean(false);
    private int reconnectAttempts = 0;
    private static final int MAX_RECONNECT_ATTEMPTS = 10;
    
    /**
     * 应用启动完成后检查MQTT连接状态
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        logger.info("应用启动完成，检查MQTT连接状态...");
        
        try {
            // 检查MQTT适配器状态
            if (mqttAdapter != null) {
                logger.info("MQTT适配器已初始化");
                
                // 启动MQTT连接
                startMqttConnection();
            } else {
                logger.warn("MQTT适配器未找到，请检查配置");
            }
            
        } catch (Exception e) {
            logger.error("启动MQTT连接时发生错误", e);
        }
    }
    
    /**
     * 启动MQTT连接
     */
    private void startMqttConnection() {
        if (isConnecting.compareAndSet(false, true)) {
            try {
                if (!mqttAdapter.isRunning()) {
                    logger.info("正在启动MQTT连接...");
                    mqttAdapter.start();
                    logger.info("MQTT连接已启动");
                    reconnectAttempts = 0; // 重置重连计数
                } else {
                    logger.info("MQTT连接已在运行中");
                }
            } catch (Exception e) {
                logger.error("启动MQTT连接失败", e);
                handleConnectionError();
            } finally {
                isConnecting.set(false);
            }
        }
    }
    
    /**
     * 处理连接错误
     */
    private void handleConnectionError() {
        reconnectAttempts++;
        if (reconnectAttempts <= MAX_RECONNECT_ATTEMPTS) {
            logger.warn("MQTT连接失败，第{}次重连尝试将在30秒后进行...", reconnectAttempts);
        } else {
            logger.error("MQTT连接失败次数过多，停止自动重连");
        }
    }
    
    /**
     * 定时检查MQTT连接状态并尝试重连
     * 每60秒检查一次，更保守的检查间隔
     */
    @Scheduled(fixedDelay = 60000)
    public void checkMqttConnection() {
        if (mqttAdapter == null) {
            return;
        }
        
        try {
            if (!mqttAdapter.isRunning()) {
                logger.warn("检测到MQTT连接已断开");
                
                if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
                    logger.info("尝试重新连接MQTT...");
                    startMqttConnection();
                } else {
                    logger.error("MQTT重连次数已达上限，请检查网络连接和服务器状态");
                }
            } else {
                // 连接正常，重置重连计数
                if (reconnectAttempts > 0) {
                    logger.info("MQTT连接已恢复正常");
                    reconnectAttempts = 0;
                }
            }
        } catch (Exception e) {
            logger.error("检查MQTT连接状态时发生错误", e);
        }
    }
    
    /**
     * 手动重连方法
     */
    public void manualReconnect() {
        if (mqttAdapter != null) {
            logger.info("执行手动重连...");
            reconnectAttempts = 0; // 重置重连计数
            startMqttConnection();
        } else {
            logger.warn("MQTT适配器未初始化，无法执行重连");
        }
    }
    
    /**
     * 获取连接状态
     */
    public boolean isConnected() {
        return mqttAdapter != null && mqttAdapter.isRunning();
    }
    
    /**
     * 获取重连尝试次数
     */
    public int getReconnectAttempts() {
        return reconnectAttempts;
    }
} 